using IdGen;

namespace UserManagement.Util;

public class SnowflakeIdGenerator
{
    private static readonly IdGenerator _generator;

    static SnowflakeIdGenerator()
    {
        var machineId = GetMachineId();
        var options = CreateIdGeneratorOptions();
        _generator = new IdGenerator(machineId, options);
    }

    private static int GetMachineId()
    {
        var machineId = int.TryParse(Environment.GetEnvironmentVariable("MACHINE_ID"), out var id) 
            ? id 
            : 0; // 默认0号机器 
        if (machineId < 0 || machineId >= 64)
            throw new ArgumentException("Machine ID must be between 0 and 63.");
        
        return machineId;
    }

    private static IdGeneratorOptions CreateIdGeneratorOptions()
    {
        return new IdGeneratorOptions(
            idStructure: new IdStructure(40, 6, 17),
            timeSource: new DefaultTimeSource(new DateTime(2023, 1, 1, 0, 0, 0, DateTimeKind.Utc)),
            sequenceOverflowStrategy: SequenceOverflowStrategy.SpinWait
        );
    }

    public static long CreateId() => _generator.CreateId();

    public static IEnumerable<long> CreateIds(int count)
    {
        if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));
        return _generator.Take(count);
    }
}